package com.hzk.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzk.exception.GabalException;
import com.hzk.mapper.UserBasicMapper;
import com.hzk.pojo.LoginState;
import com.hzk.pojo.UserBasic;
import com.hzk.service.ILoginStateService;
import com.hzk.service.IUserBasicService;
import com.hzk.utils.CookiesUtil;
import com.hzk.utils.IpUtil;
import com.hzk.utils.MD5Util;
import com.hzk.utils.UUIDUtil;
import com.hzk.vo.RespBean;
import com.hzk.vo.RespBeanEnum;
import com.hzk.vo.loginVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author jack
 * @since 2022-02-25
 */
@Service
@Component
@Slf4j
public class UserBasicServiceImpl extends ServiceImpl<UserBasicMapper, UserBasic> implements IUserBasicService {
    @Autowired
    private UserBasicMapper userBasicMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private ILoginStateService loginStateService;

    /*前端传一个post表单给后端直接能够作为一个login对象进行传输*/
    public RespBean login(loginVo loginVo, HttpServletRequest request, HttpServletResponse response) {

        String mobile = loginVo.getMobile();
        String password = loginVo.getPASSWORD();

        UserBasic userBasic = userBasicMapper.selectById(mobile);
        if (userBasic == null) {
            /*return RespBean.error(RespBeanEnum.NULL_USER_ERROR);*/
            throw new GabalException(RespBeanEnum.NULL_USER_ERROR);
        }
        String s = MD5Util.formPassToDBPass(password, "1a2b3c");
        if (!(s.equals(userBasic.getPassword()))) {
            throw new GabalException(RespBeanEnum.PASSWORD_ERROR);
        }/*b7797cce01b4b131b433b6acf4add449*/
        String Nowip = IpUtil.getIpAddress(request);
        List<LoginState> list = loginStateService.findListByid(userBasic.getId());
        if (list.size() < 3) {
            try {
                LoginState loginState = new LoginState();
                loginState.setLoginTime(1);
                loginState.setUsername(userBasic.getUsername());
                loginState.setId(userBasic.getId());
                loginState.setIpaddress(Nowip);
                loginStateService.save(loginState);
            } catch (Exception ex) {
                //设置ip和id号是唯一的主键，抛出主键异常时就执行下面方法
                loginStateService.update(new UpdateWrapper<LoginState>()
                        .setSql("login_time=" + "login_time+1")
                        .eq("id", userBasic.getId())
                        .eq("ipaddress", Nowip));
                log.info(ex.getMessage());
                String token = UUIDUtil.uuid();
                log.info(token);
                /*登录成功之后用户获得cookies ，把这些cookies存进session里面(登陆状态)*/
                redisTemplate.opsForValue().set("UserBasic:" + token, userBasic, 30, TimeUnit.MINUTES);
                return RespBean.success(token);
            }
        } else {
            return RespBean.error(RespBeanEnum.LOGIN_IPS_REFULS);
        }
        String token = UUIDUtil.uuid();
        log.info(token);
        /*登录成功之后用户获得cookies ，把这些cookies存进session里面(登陆状态)*/
        redisTemplate.opsForValue().set("UserBasic:" + token, userBasic);
        /*CookiesUtils.setCookie(request, response, "userTicket", ticket);*/
        /* CookiesUtil.writeLoginToken(request, response, token);*/

        return RespBean.success(token);
    }

    /**
     * 根据ticket
     * 去redis里面查询 user对象并返回
     */
    @Override
    public UserBasic getUserByCookies(String s, HttpServletResponse response, HttpServletRequest request) {
        if (s == null) {
            return null;
        }
        UserBasic user = (UserBasic) redisTemplate.opsForValue().get("UserBasic:" + s);
        if (!(user == null)) {
            CookiesUtil.writeLoginToken(request, response, s);
        }
        return user;
    }

    @Override
    public RespBean updatePassword(HttpServletResponse response, HttpServletRequest request, String userTicket, String password) {
        UserBasic user = getUserByCookies(userTicket, response, request);
        if (user == null) {
            throw new GabalException(RespBeanEnum.NULL_USER_ERROR);
        }
        user.setPassword(MD5Util.formPassToDBPass(password, "1a2b3c4d"));
        if (userBasicMapper.updateById(user) == 1) {
            redisTemplate.delete("UserBasic:" + userTicket);
            return RespBean.success();
        }
        return RespBean.error(RespBeanEnum.UPDATE_PASSWORD_ERROR);
    }



}

